/*******************************************************************************
 * Copyright (c) Jonathan Buck - jonbuck16@gmail.com
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    jonbuck16@gmail.com - initial API and implementation
 *******************************************************************************/
package net.jonbuck.tassoo.ui.view.comparator;

import java.util.Date;

import net.jonbuck.tassoo.model.Task;

import org.apache.commons.lang.math.NumberUtils;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;

/**
 * 
 * 
 * @since 1.0.0
 */
public class TasksViewComparator extends ViewerComparator {

	/** ... */
	private int direction = SWT.None;

	/** ... */
	private int treeColumn;

	/**
	 * 
	 */
	public int compare(Viewer viewer, Object e1, Object e2) {
		int rc = 0;
		Task task1 = (Task) e1;
		Task task2 = (Task) e2;
		if (direction == SWT.NONE) {
			rc = NumberUtils.compare(task1.getPosition(), task2.getPosition());
		} else {
			switch (treeColumn) {
			case 0:
				rc = task1.getTaskName().compareTo(task2.getTaskName());
				break;
			case 1:
				rc = task1.getCategory().getValue().compareTo(task2.getCategory().getValue());
				break;
			case 2:
				rc = task1.getPriority().getValue().compareTo(task2.getPriority().getValue());
				break;
			case 3:
				rc = task1.getType().getValue().compareTo(task2.getType().getValue());
				break;
			case 4:
				rc = task1.getStatus().getValue().compareTo(task2.getStatus().getValue());
				break;
			case 5:
				rc = NumberUtils.compare(task1.getStatus().getAssociatedPercentage(), task2.getStatus().getAssociatedPercentage());
				break;
			case 6:
				rc = compareDates(task1.getDueDate(), task2.getDueDate());
				break;
			case 7:
				rc = compareDates(task1.getCompletedDate(), task2.getCompletedDate());
				break;
			case 8:
				// ?
			case 9:
				// ?
			}

			// If descending order, flip the direction
			if (direction == SWT.DOWN) {
				rc = -rc;
			}
		}
		
		return rc;
	}

	/**
	 * 
	 * @param strDate1
	 * @param strDate2
	 * @return
	 */
	private int compareDates(Date strDate1, Date strDate2) {
		if (strDate1 == null | strDate2 == null) {
			return 0;
		}
		if (strDate1.after(strDate2)) {
			return 1;
		}
		if (strDate1.before(strDate2)) {
			return -1;
		}
		return 0;
	}

	/**
	 * 
	 * @param trclmn
	 */
	public void setColumn(int trclmn) {
		this.treeColumn = trclmn;
	}

	/**
	 * 
	 * @param dir
	 */
	public void setDirection(int dir) {
		this.direction = dir;
	}

}
